/*
  Author: Ionel Crisu - crisuionel@yahoo.com
  support@FlashExtended.com
*/
package com.flashextended.utils.server.assetloader
{
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	import mx.controls.Alert;

	public class AssetURLLoader extends URLLoader
	{
		private var request:URLRequest;
		public var status:String = "FAIL";
		private var isErrorMsg:Boolean = true;
		private var callBack:Function;
		
		private const ERR_TITLE:String = "Error";
		private const SECURITY_ERR:String = "Security Error!, please chech the crossdomain.xml";
		private const IO_ERROR_ER:String = "IO Error!, please chech your server side script";
				
		public function AssetURLLoader(request:URLRequest=null, callBack:Function=null)
		{
			super(request);
			this.callBack = callBack;
			//this.request = new URLRequest(url);
			//super(request);
			this.addEventListener(Event.COMPLETE, completed);
			this.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
			this.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);		
		}
		public function start():void
		{
			this.load(request);
		}
		private function completed(e:Event):void
		{
			status = "OK";
			this.dispatchEvent(new Event("change"));
			try{
				callBack(loader);
			}catch(e:Error)
			{
				Alert.show(e.message);
			}
		}
		private function ioErrorHandler(e:IOErrorEvent):void
		{
			status = "FAIL";
			this.dispatchEvent(new Event("change"));
			(isErrorMsg)?Alert.show(IO_ERROR_ER, ERR_TITLE):null;
		}
		private function securityErrorHandler(e:SecurityErrorEvent):void
		{
			status = "FAIL";
			this.dispatchEvent(new Event("change"));
			(isErrorMsg)?Alert.show(SECURITY_ERR, ERR_TITLE):null;
		}
		
		//change data format
		public function changeDataFormat(dataF:String):void
		{
			this.dataFormat = dataF;
		}
		public function get loader():Loader
		{
			var l:Loader = new Loader;
			l.loadBytes(this.data);
			return l;
		}
		
		//implement alert errors
		public function set implementErrorMessages(val:Boolean):void
		{
			isErrorMsg = val;
		}		
		
	}
}